package cn.wolfcode.wms.web.interceptor;

import java.lang.reflect.Method;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.util.RequiredPermission;
import cn.wolfcode.wms.util.UserContext;

public class SecurityInterceptor extends HandlerInterceptorAdapter{
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		Set<String> expressions = UserContext.getExpressions();
		Employee currentUser = UserContext.getUser();
		
		//判断用户是否是超级用户
		if (currentUser.isAdmin()) {
			//是放行
			return true;
		}
		//获取当前用户访问的方法
		HandlerMethod hm = (HandlerMethod)handler;
		Method method = hm.getMethod();
		//判断当前方法是否要权限
		if (!method.isAnnotationPresent(RequiredPermission.class)) {
			//否 放行
			return true;
		}
		//拼接当前访问的资源表达式
		String ex = hm.getBeanType().getName() + ":" + method.getName();
		//判断当前用户是否有权限
		if (expressions.contains(ex)) {
			//有 放行
			return true;
		}
		//否  提示页面
		response.sendRedirect("/nopermission.html");
		return false;
	}

}
